package com.zjl.legendary.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author zhoujingluo
 * @date 2021/6/7 16:32
 */
public class MyBatisUtils {
    /**
     * 获得工厂对象
     */
    private static SqlSessionFactory factory;

    /**
     * 创建ThreadLocal绑定当前线程中的SqlSession对象
     */
    private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();

    static{
        try {
            InputStream ris = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(ris);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得sqlSession会话对象
     * @return
     */
    public static SqlSession openSession(){
        SqlSession sqlSession = THREAD_LOCAL.get();
        if (sqlSession == null) {
            sqlSession = factory.openSession();
            THREAD_LOCAL.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 释放连接(释放当前线程中的sqlSession)
     */
    public static void closeSession(){
        SqlSession sqlSession = openSession();
        sqlSession.close();
        THREAD_LOCAL.remove();
    }

    /**
     * 提交事务
     */
    public static void commit(){
        SqlSession sqlSession = openSession();
        sqlSession.commit();
        closeSession();
    }

    /**
     * 回滚事务
     */
    public static void rollback(){
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
        closeSession();
    }

    /**
     * 获得接口实现类对象
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T extends Object> T getMapper(Class<T> clazz){
        SqlSession sqlSession = openSession();
        return sqlSession.getMapper(clazz);
    }
}
